//
//  ZDBBindWXViewController.m
//  ZDB
//
//  Created by Kk on 2020/3/24.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBBindWXViewController.h"
#import "SC_ActionSheet.h"

@interface ZDBBindWXViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate>
@property(nonatomic,assign)BOOL isLeft;
@property(strong,nonatomic)NSString * kUploadIconImageToken;
@property(nonatomic,strong)NSMutableArray * images;
@property(nonatomic,strong)NSMutableArray * imagkeys;//上传成功之后的key
@end

@implementation ZDBBindWXViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"审核资质";
    _images = [NSMutableArray new];
   
     WeakSelf
    [self.wx_PositiveBtn add_BtnClickHandler:^(NSInteger tag) { //第一个视图
        weakSelf.isLeft = YES;
        [weakSelf uploadImage];
    }];
    [self.wx_versobtn add_BtnClickHandler:^(NSInteger tag) { //第二个图
          weakSelf.isLeft = NO;
          [weakSelf uploadImage];
    }];
    [self.deleteBtn add_BtnClickHandler:^(NSInteger tag) {
        [weakSelf deletImage:weakSelf.deleteBtn];
    }];
    [self.right_deleteBtn add_BtnClickHandler:^(NSInteger tag) {
        [weakSelf deletImage:weakSelf.right_deleteBtn];
    }];
   
    self.deleteBtn.hidden =  self.right_deleteBtn.hidden =YES;
    [self.saveBtn add_BtnClickHandler:^(NSInteger tag) {//保存
        [weakSelf uploadWx];
    }];
    [self getAvatarQiniuToken];
}
//获取七牛头像token
-(void)getAvatarQiniuToken{
    [self showLoadingAnimation];
    WEAKSELF
    [[SmileHttpTool sharedInstance] getTokenFromQiNiu:@"" resultBlock:^(BOOL isSuccess, NSString *token) {
        [self stopLoadingAnimation];
        STRONGSELFFor(weakSelf)
        if (isSuccess) {
            strongSelf.kUploadIconImageToken = token;
           
        }else
        {
            [JMNotifyView showNotify:token isSuccessful:NO];
        }
    }];
}
- (void)uploadWx
{
    if (_images.count<2)
    {
        [JMNotifyView showNotify:@"请选择上传微信好友通讯录截图与微信个人信息页面截图" isSuccessful:NO];
        return;
    }
    if (kStringIsEmpty(_nameTextField.text))
    {
        [JMNotifyView showNotify:@"请输入微信昵称" isSuccessful:NO];
        return;
    }
    if (kStringIsEmpty(_numTextField.text))
    {
        [JMNotifyView showNotify:@"请输入微信账号" isSuccessful:NO];
        return;
    }
    if ([ZBDUnit JudgeTheillegalCharacter:_nameTextField.text])
    {
        [JMNotifyView showNotify:@"昵称不能包含特殊字符" isSuccessful:NO];
        return;
    }
     self.saveBtn.userInteractionEnabled = NO;
    if (self.kUploadIconImageToken)
    {
        __block ZDBCustomerAlearView * custom = [[ZDBCustomerAlearView alloc] initWithtititle:@"温馨提示" content:@"审核任务时，需要用户昵称与微信昵称保持一致，是否同步修改用户昵称" cancel:@"稍后修改" submit:@"确定同步"];
        [custom showLXAlertView];
        WeakSelf
        [custom.cancelBtn add_BtnClickHandler:^(NSInteger tag) {//取消
            
             [custom dismissAlertView];
             weakSelf.saveBtn.userInteractionEnabled = YES;
        }];
        [custom.submitBtn add_BtnClickHandler:^(NSInteger tag) {
            [custom dismissAlertView];
            
            [self showLoadingAnimation];
            weakSelf.imagkeys = [NSMutableArray new];
            QNUploadManager *upManager = [[QNUploadManager alloc] init];
            [self uploadImages:weakSelf.images atIndex:0 token:weakSelf.kUploadIconImageToken uploadManager:upManager keys:weakSelf.imagkeys];
            
        }];
       
        
    }else
    {
        [self getAvatarQiniuToken];
    }
   
}
- (void)uploadImage {

    WeakSelf
    if (weakSelf.images.count==2) {
        return;
    }
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:2 - weakSelf.images.count  delegate:self];
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowPickingGif = NO;
    if (@available(iOS 13.0, *)) {
        imagePickerVc.statusBarStyle = UIStatusBarStyleDarkContent;
    } else {
        imagePickerVc.statusBarStyle = UIStatusBarStyleDefault;
      
    }
    imagePickerVc.alwaysEnableDoneBtn = YES;
    imagePickerVc.allowPickingVideo = NO; //不许选择视频
    imagePickerVc.allowPickingMultipleVideo = NO;//不允许选择视频gif
    imagePickerVc.barItemTextColor = [UIColor colorWithHexString:@"#333333"];
    imagePickerVc.naviTitleColor = [UIColor colorWithHexString:@"#333333"];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        for (UIImage * image in photos)
        {
            [weakSelf.images addObject:image];
        }
        [self imageData:weakSelf.images];
     
    }];
    imagePickerVc.modalPresentationStyle = 0;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}
- (void)deletImage:(UIButton *)sender
{
    if (sender.tag==0) {
         [self.images removeObjectAtIndex:0];
         sender.hidden = YES;
        [_wx_PositiveBtn setImage:[UIImage imageNamed:@"add_alipay"] forState:0];
    }else
    {
        if (self.images.count>1) {
            [self.images removeObjectAtIndex:1];
        }else
        {
            [self.images removeObjectAtIndex:0];
        }
        
        sender.hidden = YES;
        [_wx_versobtn setImage:[UIImage imageNamed:@"add_alipay"] forState:0];
    }
   
}
- (void)imageData:(NSMutableArray *)photos
{
    if (photos.count ==1)
    {
        self.deleteBtn.hidden = NO;
        [_wx_PositiveBtn setImage:photos[0] forState:0];
    }else
    {
         self.deleteBtn.hidden = NO;
         self.right_deleteBtn.hidden = NO;
        [_wx_PositiveBtn setImage:photos[0] forState:0];
        [_wx_versobtn setImage:photos[1] forState:0];
    }
}
-(void)uploadImages:(NSArray *)images atIndex:(NSInteger)index token:(NSString *)token uploadManager:(QNUploadManager *)uploadManager keys:(NSMutableArray *)keys;{
    UIImage *image = images[index];
    __block NSInteger imageIndex = index;
    NSData *data = UIImageJPEGRepresentation(image, 0.8);
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    WeakSelf
    NSString *key = [NSString stringWithFormat:@"iOS%@.jpg", [formatter stringFromDate:[NSDate date]]];
    [uploadManager putData:data key:key token:token
                  complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                      if (info.isOK) {
                          [keys addObject:key];
                          imageIndex++;
                          if (imageIndex >= images.count) {
                              NSLog(@"上传完成");
                              [weakSelf uploadBindWXWithImageKeys:keys];
                              return ;
                          }
                          [self uploadImages:images atIndex:imageIndex token:token uploadManager:uploadManager keys:keys];
                      }else
                      {
                          [self stopLoadingAnimation];
                          weakSelf.saveBtn.userInteractionEnabled = YES;
                           [JMNotifyView showNotify:@"上传照片失败" isSuccessful:NO];
                      }
         
    } option:nil];
}
- (void)uploadBindWXWithImageKeys:(NSMutableArray *)imagekeys
{
    NSLog(@"====>%@",imagekeys);
    
    NSMutableString * keymustr = [[NSMutableString alloc] init];;
    for (NSString * imageFile in imagekeys)
    {
        [keymustr appendString:kFormat(@"%@,",imageFile)];
    }
    NSRange deleteRange = {[keymustr length] - 1, 1 };
    [keymustr deleteCharactersInRange:deleteRange];
    
    NSMutableDictionary * diccc = [NSMutableDictionary dictionary];
    [diccc setValue:keymustr forKey:@"images"];
    [diccc setValue:_nameTextField.text forKey:@"wxNikeName"];
    [diccc setValue:_numTextField.text forKey:@"wxNumber"];
    
    WeakSelf
    NSString  * bandWxNumber = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"bandWxNumber"];
    [[SmileHttpTool sharedInstance] POST:bandWxNumber parameters:diccc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
        if (statusCode ==0)  {
            [JMNotifyView showNotify:@"微信资质提交请耐心等待" isSuccessful:NO];
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [[DJLoginHelper sharedInstance] saveWXExamineType:@"1"];//保存审核状态
        }else
        {
            [JMNotifyView showNotify:message isSuccessful:NO];;
        }
        weakSelf.saveBtn.userInteractionEnabled = YES;
       [self stopLoadingAnimation];
        
    } failure:^(id responseObject, NSError *error) {
        weakSelf.saveBtn.userInteractionEnabled = YES;
        [self stopLoadingAnimation];
    }];
}
@end
